// ==UserScript==
// @name         爱启航视频快捷键
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  给视频界面增加一些快捷键
// @author       HqLin
// @match        https://www.iqihang.com/recordedCC
// @grant        none
// ==/UserScript==

'use strict';

function is_open(dir: HTMLElement | null): boolean {
    return dir?.getElementsByClassName("video_list").length != 0;
}

function next(curr: Element | null) {
    let next = curr?.nextElementSibling?.querySelector("li");
    if (next != null) {
        next.click();
    } else {
        let nextDir = <HTMLElement | null>curr
            ?.parentElement?.parentElement
            ?.nextElementSibling;
        if (!is_open(nextDir)) {
            nextDir?.querySelector("div")?.click();
        }
        // 监听目录出现
        new MutationObserver((_, ob) => {
            const f = <HTMLElement>nextDir?.querySelector(".video_list li");
            if (f != null) {
                f.click();
                ob.disconnect();
            }
        }).observe(<Node>document.querySelector(".chapyer_wraps"),
            { subtree: true, childList: true });
    }
}

function previous(curr: Element | null) {
    let next = curr?.previousElementSibling?.querySelector("li");
    if (next != null) {
        next.click();
    } else {
        let previousDir = <HTMLElement | null>curr?.parentElement?.parentElement?.previousElementSibling;
        if (!is_open(previousDir)) {
            previousDir?.querySelector("div")?.click();
        }

        new MutationObserver((_, ob) => {
            const v_list = previousDir?.querySelectorAll(".video_list li")
            if (v_list != null) {
                const f = <HTMLElement>v_list[v_list?.length - 1];
                if (f != null) {
                    f.click();
                    ob.disconnect();
                }
            }
        }).observe(<Node>document.querySelector(".chapyer_wraps"), { subtree: true, childList: true });
    }
}

(() => {
    let curr: HTMLElement | null;
    console.warn("快捷键已加载，使用j/k进行切换")
    document.body.addEventListener("keydown", e => {
        switch (e.key) {
            case 'k':
                curr = document.querySelector(".video_list.active");
                previous(curr);
                break;
            case 'j':
                curr = document.querySelector(".video_list.active");
                next(curr);
                break;
            default:
                console.log(e.key)
        }
    });
})()